<?php
namespace app\logic;

use app\common\corelib\CacheHelper;
use app\common\HttpCurl;
use app\common\PayMethodEnum;
use app\common\PayUtil;
use app\models\CustomerService;
use app\models\Express;
use app\models\Goods;
use app\models\GoodsSku;
use app\models\OrderGoods;
use app\models\Package;
use app\models\Order;
use app\models\ServiceLog;
use Beanstalk\Client;


class OrderLogic
{
    public function createCancelNo(){
        return mt_rand(10000000,99999999);
        /*$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        return $yCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));*/
    }

    public function createOrderNo(){
        return date('Ymd').mt_rand(100000,999999);
        /*$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        return $yCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));*/
    }

    public function getToBePaid($user_id){
        return Order::find()->where(['user_id'=>$user_id,'order_status'=>0])->count();
    }
    public function getPendingDelivery($user_id){
        return Package::find()
            ->from('{{%package}} p')
            ->leftJoin('{{%order}} o', 'o.order_id=p.order_id')
            ->where(['o.user_id'=>$user_id,'package_status'=>2])->count('package_id');
    }
    public function getShippinged($user_id){
        return Package::find()
            ->from('{{%package}} p')
            ->leftJoin('{{%order}} o', 'o.order_id=p.order_id')
            ->where(['o.user_id'=>$user_id,'package_status'=>4])->count('package_id');
    }

    public function paySuccess($order_no,$pay_time,$pay_no,$thirdPartyCode,&$order_id){
        $db=\Yii::$app->db;
        $transaction = $db->beginTransaction();
        $order = Order::findOne(['order_no'=>$order_no]);
        if($order->order_status==0){
            $order->order_status = 1;
            $time = date('Y-m-d H:i:s');
            $payMethodEnum = new PayMethodEnum();
            $payMethod = isset($payMethodEnum->$thirdPartyCode)?$payMethodEnum->$thirdPartyCode:$thirdPartyCode;
            $order->pay_type = $payMethod;
            $order->pay_time = date('Y-m-d H:i:s',strtotime($pay_time));
            $order->pay_no = $pay_no;
            $order->update_time = $time;
            $result1 = $order->save();
            $order_id = $order->order_id;
            $skutemp = OrderGoods::find()->where(['order_id'=>$order_id])->asArray()->all();
            $goods_sale_volume = [];
            $result5 = true;
            foreach($skutemp AS $key=>$value){
                if(isset($goods_sale_volume[$value['goods_id']])){
                    $goods_sale_volume[$value['goods_id']] += $value['buy_num'];
                }else{
                    $goods_sale_volume[$value['goods_id']] = $value['buy_num'];
                }
                $sku[$key]['skuId'] = $value['yx_sku_id'];
                $sku[$key]['productName'] = $value['goods_name'];
                $sku[$key]['saleCount'] = $value['buy_num'];
                $sku[$key]['originPrice'] = $value['channel_price'];
                $sku[$key]['subtotalAmount'] = $value['channel_price']*$value['buy_num'];
                $goodsSku = GoodsSku::findOne($value['sku_id']);
                $goodsSku->sku_sales_volume += $value['buy_num'];
                $result5 &= $goodsSku->save();
            }
            $result3 = true;
            foreach($goods_sale_volume AS $kk=>$vv){
                $goods = Goods::findOne($kk);
                $goods->sales_volume += $vv;
                $result3 &= $goods->save();
            }
            $order = [
                'orderId'=>$order_no,
                'submitTime'=>$order->order_time,
                'payTime'=>$order->pay_time,
                'receiverName'=>$order->consignee,
                'receiverPhone'=>$order->consignee_phone,
                'receiverProvinceName'=>$order->consignee_province,
                'receiverCityName'=>$order->consignee_city,
                'receiverDistrictName'=>$order->consignee_district,
                'receiverAddressDetail'=>$order->consignee_address,
                'realPrice'=>$order->channel_amount+$order->shipping_fee,
                'expFee'=>$order->shipping_fee,
                'payMethod'=>$thirdPartyCode,                                //此处
                'orderSkus'=>$sku
            ];
            $httpCurl = new HttpCurl();
            $result = $httpCurl->rollpost("yanxuan.order.paid.create",['order'=>json_encode($order)]);
            $result = json_decode($result,true);
            $result2 = true;
            $result4 = true;
            foreach($result['orderPackages'] AS $key=>$value){
                $package = new Package();
                $package->yx_package_id = $value['packageId'];
                $package->order_id = $order_id;
                $package->package_status = 2;
                $result2 &= $package->save();
                $skus = $value['orderSkus'];
                foreach($skus AS $kk=>$vv){
                    $og = OrderGoods::findOne(['order_id'=>$order_id,'yx_sku_id'=>$vv['skuId']]);
                    $og->package_id = $package->package_id;
                    $result4 &= $og->save();
                }
            }
            if($result1 && $result2 && $result3 && $result4 && $result5){
                $transaction->commit();
                return true;
            }else{
                $transaction->rollBack();
                return false;
            }
        }else{
            return false;
        }

    }

    public function addPackage($order_id,$yx_package){
        $package = new Package();
        $package->order_id = $order_id;
        $package->yx_package_id = $yx_package['packageId'];
        $package->save();
    }

    public function beanstalkProducer($id,$type,$delay){
        $beanstalk = new Client(); // For connection options see the
        // class documentation.
        $beanstalk->connect();
        $beanstalk->useTube('order'); // Begin to use tube `'flux'`.
        $beanstalk->put(
            1, // Give the job a priority of 23.
            $delay,  // Do not wait to put job into the ready queue.
            60, // Give the job 1 minute to run.
            json_encode(['id'=>$id,'type'=>$type]) // The job's body.
            //$type=1:自动取消订单，$type=2:自动收货
        );
        $beanstalk->disconnect();
    }

    public function getOrderList($user_id,$page,$limit,$order_status,$return){
        if($return){
            $package = Package::find()
                ->select('p.order_id,sum(p.package_status) as pasum')
                ->from('{{%package}} p')
                ->leftJoin('{{%order}} o', 'o.order_id=p.order_id')
                ->where(['o.user_id'=>$user_id,'o.order_status'=>4])
                ->groupBy('order_id')
                ->having('pasum!=0')
                ->orderBy('order_id desc')
                ->offset($limit*($page-1))->limit($limit)
                ->asArray()->all();
            $order_ids = array_column($package,'order_id');
            return Order::find()
                ->select('order_id,order_no,order_amount as total_amount,order_status')
                ->where(['user_id'=>$user_id,'order_id'=>$order_ids])
                ->orderBy('order_id desc')
                ->offset($limit*($page-1))->limit($limit)
                ->asArray()->all();
        }else{
            if($order_status!=-1){
                return Order::find()
                    ->select('order_id,order_no,order_amount as total_amount,order_status')
                    ->where(['user_id'=>$user_id,'order_status'=>$order_status])
                    ->orderBy('order_id desc')
                    ->offset($limit*($page-1))->limit($limit)
                    ->asArray()->all();
            }else{
                return Order::find()
                    ->select('order_id,order_no,order_amount as total_amount,order_status')
                    ->where(['user_id'=>$user_id])
                    ->orderBy('order_id desc')
                    ->offset($limit*($page-1))->limit($limit)
                    ->asArray()->all();
            }
        }
    }

    public function getOrderSkus($order_ids){
        return OrderGoods::find()
            ->select('og.sku_id,og.sku_pic,og.goods_name,og.sku_price,og.sku_spec,og.goods_id,og.buy_num as num,p.package_status,o.order_status,og.package_id,og.order_id')
            ->from('{{%order_goods}} og')
            ->leftJoin('{{%package}} p', 'p.package_id=og.package_id')
            ->leftJoin('{{%order}} o', 'o.order_id=og.order_id')
            ->where(['og.order_id'=>$order_ids])
            ->asArray()->all();
    }

    public function getOrderSkusCount($order_ids){
        return OrderGoods::find()
            ->select('order_id,sum(buy_num) as total_num')
            ->where(['order_id'=>$order_ids])
            ->groupBy('order_id')
            ->asArray()->all();
    }

    public function cancelOrder($order_no,&$rejectReason=null){
        $order = Order::findOne(['order_no'=>$order_no]);
        if($order->order_status == 0){
            $db=\Yii::$app->db;
            $transaction = $db->beginTransaction();
            $time = date('Y-m-d H:i:s');
            $order->update_time = $time;
            $order->order_status = 2;
            $result2 = true;
            $packages = Package::findAll(['order_id'=>$order->order_id]);
            foreach($packages AS $key=>$value){
                $value->package_status = 3;
                $value->update_time = $time;
                $result2 &= $value->save();
            }
            $result1 = $order->save();
            if($result1 && $result2){
                $transaction->commit();
                return true;
            }else{
                $transaction->rollBack();
                return false;
            }
        }else{
            $httpCurl = new HttpCurl();
            $result = $httpCurl->rollpost("yanxuan.order.paid.cancel",['orderId'=>$order_no]);
            $result = json_decode($result,true);
            if($result['cancelStatus']==1){
                $db=\Yii::$app->db;
                $transaction = $db->beginTransaction();

                $time = date('Y-m-d H:i:s');
                $order->update_time = $time;
                $order->order_status = 2;
                $result2 = true;
                $packages = Package::findAll(['order_id'=>$order->order_id]);
                foreach($packages AS $key=>$value){
                    if($value->package_status!=2){
                        return false;
                    }
                    $value->package_status = 3;
                    $value->update_time = $time;
                    $result2 &= $value->save();
                }
                $result1 = $order->save();
                if($result1 && $result2){
                    $transaction->commit();
                    return true;
                }else{
                    $transaction->rollBack();
                    return false;
                }
            }elseif($result['cancelStatus']==2){
                $db=\Yii::$app->db;
                $transaction = $db->beginTransaction();
                $order = Order::findOne(['order_no'=>$order_no]);
                $time = date('Y-m-d H:i:s');
                $order->update_time = $time;
                $order->order_status = 5;
                $result2 = true;
                /*$packages = Package::findAll(['order_id'=>$order->order_id]);
                foreach($packages AS $key=>$value){
                    if($value->package_status!=2){
                        return false;
                    }
                    $value->package_status = 3;
                    $value->update_time = $time;
                    $result2 &= $value->save();
                }*/
                $result1 = $order->save();
                if($result1 && $result2){
                    $transaction->commit();
                    return true;
                }else{
                    $transaction->rollBack();
                    return false;
                }
            }else{
                $rejectReason = $result['rejectReason'];
                $order = Order::findOne(['order_no'=>$order_no]);
                $time = date('Y-m-d H:i:s');
                $order->update_time = $time;
                $order->reject_reason = $rejectReason;
                $order->save();
                return false;
            }
        }


    }

    public function cancelCallback($orderCancelResult){
        $db=\Yii::$app->db;
        $transaction = $db->beginTransaction();
        $orderCancelResult = json_decode($orderCancelResult,true);
        if($orderCancelResult['cancelStatus']){
            $order = Order::findOne(['order_no'=>$orderCancelResult['orderId']]);
            $time = date('Y-m-d H:i:s');
            $order->update_time = $time;
            $order->order_status = 2;
            $result2 = true;
            $packages = Package::findAll(['order_id'=>$order->order_id]);
            foreach($packages AS $key=>$value){
                if($value->package_status!=2){
                    return false;
                }
                $value->package_status = 3;
                $value->update_time = $time;
                $result2 &= $value->save();
            }
            $result1 = $order->save();
            if($result1 && $result2){
                $transaction->commit();
            }else{
                $transaction->rollBack();
            }
        }else{
            $order = Order::findOne(['order_no'=>$orderCancelResult['orderId']]);
            $time = date('Y-m-d H:i:s');
            $order->update_time = $time;
            $order->reject_reason = $orderCancelResult['rejectReason'];
            $order->save();
        }

    }

    public function confirmPackage($package_id){
        $db=\Yii::$app->db;
        $transaction = $db->beginTransaction();
        $package = Package::findOne(['package_id'=>$package_id]);
        $order = Order::findOne($package->order_id);
        if($package->package_status!=4)
            return false;
        $package->package_status = 5;
        $time = date('Y-m-d H:i:s');
        $package->update_time = $time;
        $result1 = $package->save();
        $allok = true;
        $packages = Package::find()->where(['order_id'=>$package->order_id])->asArray()->all();
        foreach($packages AS $key=>$value){
            if($value['package_status']!=5){
                $allok &= false;
            }
        }
        $result2 = true;
        if($allok){
            $order->update_time = $time;
            $order->order_status = 4;
            $result2 = $order->save();
        }
        if($result1 && $result2){
            $transaction->commit();
            $httpCurl = new HttpCurl();
            $httpCurl->rollpost("yanxuan.order.received.confirm",['orderId'=>$order->order_no,'packageId'=>$package->yx_package_id,'confirmTime'=>$time]);
        }else{
            $transaction->rollBack();
        }
    }

    public function pay($order_no){
        $pu = new PayUtil();
        $order = Order::find()->where(['order_no'=>$order_no])->asArray()->one();
        $orderGoods = OrderGoods::find()->where(['order_id'=>$order['order_id']])->asArray()->all();
        foreach ($orderGoods AS $value){
            $goods_name = $value['goods_name'];
            break;
        }
        $url = $pu->getUrl($order_no,date('YmdHis',strtotime($order['order_time'])),$order['order_amount'],$goods_name);
        return $url;
    }

    public function delivered($orderPackage){
        $db=\Yii::$app->db;
        $transaction = $db->beginTransaction();
        $orderPackage = json_decode($orderPackage,true);
        $package = Package::findOne(['yx_package_id'=>$orderPackage['packageId']]);
        $time = date('Y-m-d H:i:s',substr($orderPackage['expCreateTime'],0,10));
        $package->update_time = $time;
        $package->package_status = 4;
        $result1 = $package->save();
        $this->beanstalkProducer($package->package_id,2,864000);
        $order = Order::findOne(['order_no'=>$orderPackage['orderId']]);
        $packages = Package::find()->where(['order_id'=>$package->order_id])->asArray()->all();
        $allok = true;
        foreach($packages AS $key=>$value){
            if($value['package_status'] != 4){
                $allok &= false;
            }
        }
        $result2 = true;
        if($allok){
            $order->update_time = $time;
            $order->order_status = 3;
            $result2 = $order->save();
        }
        $result3 = true;
        foreach($orderPackage['expressDetailInfos'] AS $k=>$v){
            $express = new Express();
            $express->order_id = $package->order_id;
            $express->package_id = $package->package_id;
            $express->express_company = $v['expressCompany'];
            $express->express_no = $v['expressNo'];
            $result3 &= $express->save();
        }

        if($result1 && $result2 && $result3){
            $transaction->commit();
        }else{
            $transaction->rollBack();
        }
    }

    public function getOrderDetail($order_no){
        return Order::find()
            ->select('order_id,order_no,order_time,goods_amount as total_price, shipping_fee,order_amount as total_amount,order_status,pay_type,pay_time,consignee as name,consignee_phone as phone,consignee_province as province,consignee_city as city,consignee_district as district,consignee_address as address')
            ->where(['order_no'=>$order_no])
            ->asArray()->one();
    }

    public function getExpress($package_id){
        return Express::find()
            ->select('e.*,o.order_no,p.yx_package_id')
            ->from('{{%express}} e')
            ->leftJoin('{{%order}} o', 'o.order_id=e.order_id')
            ->leftJoin('{{%package}} p', 'p.package_id=e.package_id')
            ->where(['e.package_id'=>$package_id])->asArray()->all();
    }

    public function getOrderSkusByPackage($package_id){
        return OrderGoods::find()
            ->select('og.sku_id,og.sku_pic,og.goods_name,og.sku_price,og.sku_spec,og.goods_id,og.buy_num as num,p.package_status,o.order_status')
            ->from('{{%order_goods}} og')
            ->leftJoin('{{%package}} p', 'p.package_id=og.package_id')
            ->leftJoin('{{%order}} o', 'o.order_id=og.order_id')
            ->where(['og.package_id'=>$package_id])
            ->asArray()->all();
    }

    public function getYetOrderSkusByPackage($package_id,$sku_ids){
        return CustomerService::find()
            ->select('cs.sku_id,cs.sku_num')
            ->from('{{%customer_service}} cs')
            ->where(['package_id'=>$package_id,'sku_id'=>$sku_ids])
            ->andWhere("yanxuan_status!=6")
            ->asArray()->all();
    }

    public function returns($user_id,$package_id,$sku_id,$num,$reason_type,$reason_detail,$service_pics,$customer_name,$customer_phone){
        $ycs = CustomerService::find()->where("user_id=$user_id AND package_id=$package_id AND sku_id=$sku_id AND (yanxuan_status<=3 OR yanxuan_status=9)")->asArray()->one();
        if($ycs)
            return false;
        $db=\Yii::$app->db;
        $transaction = $db->beginTransaction();
        $service_no = $this->createOrderNo();

        $service3 = CustomerService::findOne(['service_no'=>$service_no]);
        while($service3){
            $service_no = $this->createOrderNo();
            $service3 = CustomerService::findOne(['service_no'=>$service_no]);
        }
        $service = new CustomerService();
        $service->service_no = $service_no;
        $og = OrderGoods::find()
            ->select('og.*,o.order_no')
            ->from('{{%order_goods}} og')
            ->leftJoin('{{%order}} o', 'o.order_id=og.order_id')
            ->where(['package_id'=>$package_id,'sku_id'=>$sku_id])->asArray()->one();

        $picarr = json_decode($service_pics,true);
        $fin_pics = [];
        $fin_pics_temp = [];
        foreach ($picarr AS $key=>$value){
            if(strpos($value,'image')!==false){
                $pic = $this->changePic($value,$fileName);
                $fin_pics[] = $pic;
                $fin_pics_temp[] = [
                    'url'=> \Yii::$app->params['pic_domain'].$pic,
                    'fileName'=>$fileName
                ];
            }
        }
        $package = Package::findOne($package_id);
        $reasonDesc = $reason_detail?$reason_detail:" ";
        $data = [
            'requestId'=>$service_no,
            'orderId'=>$og['order_no'],
            'applyUser'=>[
                'name'=>$customer_name,
                'mobile'=>$customer_phone
            ],
            'applySku'=>[
                'packageId'=>$package->yx_package_id,
                'skuId'=>$og['yx_sku_id'],
                'count'=>$num,
                'applySkuReason'=>[
                    'reason'=>$reason_type?"质量问题":"无理由",
                    'reasonDesc'=>$reasonDesc
                ],
                'applyPicList'=>$fin_pics_temp,
                'originalPrice'=>$og['sku_price'],
                'subtotalPrice'=>$og['sku_price']*$num
            ]
        ];
        $httpCurl = new HttpCurl();
        $result = json_decode($httpCurl->rollpost("yanxuan.order.refund.apply",['applyInfo'=>json_encode($data)]),true);
        if(!$result){
            return false;
        }


        $service->service_no = $service_no;
        $service->order_id = $og['order_id'];
        $service->package_id = $package_id;
        $service->user_id = $user_id;
        $service->goods_id = $og['goods_id'];
        $service->goods_name = $og['goods_name'];
        $service->sku_id = $sku_id;
        $service->sku_pic = $og['sku_pic'];
        $service->sku_spec = $og['sku_spec'];
        $service->sku_price = $og['sku_price'];
        $service->sku_num = $num;
        $service->service_amount = $og['sku_price']*$num;
        $service->customer_name = $customer_name;
        $service->customer_phone = $customer_phone;
        $service->reason_type = $reason_type;
        $service->reason_detail = $reason_detail;
        $time = time();
        $service->service_time = date('Y-m-d H:i:s',$time);
        $service->service_pics = implode(',',$fin_pics);
        $service->yx_service_id = $result['applyId'];
        $result1 = $service->save();
        $serviceLog = new ServiceLog();
        $serviceLog->service_id = $service->service_id;
        $serviceLog->log_time = date('Y-m-d',$time);
        $serviceLog->log_content = "已提交退货申请，等待客服审核";
        $result2 = $serviceLog->save();

        $allok = true;
        $orderSkus = $this->getOrderSkusByPackage($package_id);
        $sku_ids = array_column($orderSkus,'sku_id');
        $yetOrderSkus = $this->getYetOrderSkusByPackage($package_id,$sku_ids);
        $fin_num = [];
        foreach($yetOrderSkus AS $key=>$value){
            $fin_num[$value['sku_id']] = $value['sku_num'];
        }
        foreach($orderSkus AS $k=>$v){
            if(isset($fin_num[$v['sku_id']])){
                if($v['num'] != $fin_num[$v['sku_id']]){
                    $allok &= false;
                }
            }else{
                $allok &= false;
            }
        }
        $result3 = true;

        if($allok){
            $package->package_status = 0;
            $result3 &= $package->save();
        }

        if($result1 && $result2 && $result3){
            $transaction->commit();
            return $service_no;
        }else{
            $transaction->rollBack();
            return false;
        }

    }

    public function changePic($pic,&$fileName){
        header('Content-type:text/html;charset=utf-8');
        $base64_image_content = $pic;
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            $fileName = time().rand(0,1000).".{$type}";
            $new_file = "/uploads/service/".$fileName;
            $new_file_temp = __DIR__.'/../../web'.$new_file;
            /*if(!file_exists($new_file))
            {
                mkdir($new_file_temp, 0700);
            }*/
            if (file_put_contents($new_file_temp, base64_decode(str_replace($result[1], '', $base64_image_content)))){
                return $new_file;
            }else{
                return false;
            }
        }
    }

    public function refundAddress($refundAddress){
        $db=\Yii::$app->db;
        $transaction = $db->beginTransaction();
        $refundAddress = json_decode($refundAddress,true);
        $service = CustomerService::findOne(['yx_service_id'=>$refundAddress['applyId']]);
        $service->yanxuan_status = 2;
        $service->zhongjing_status = 2;
        $time = time();
        $service->update_time = date('Y-m-d H:i:s',$time);
        $result1 = $service->save();
        $serviceLog = new ServiceLog();
        $serviceLog->service_id = $service->service_id;
        $serviceLog->log_time = date('Y-m-d',$time);
        $serviceLog->log_content = "客服已通过退货审核，请将商品寄到以下地址，并填写物流单号";
        $serviceLog->reciver = $refundAddress['returnAddr']['name'];
        $serviceLog->mobile = $refundAddress['returnAddr']['mobile'];
        $serviceLog->address = $refundAddress['returnAddr']['fullAddress'];
        $result2 = $serviceLog->save();
        if($result1 && $result2){
            $transaction->commit();
        }else{
            $transaction->rollBack();
        }
    }

    public function refundReject($rejectInfo){
        $db=\Yii::$app->db;
        $transaction = $db->beginTransaction();
        $rejectInfo = json_decode($rejectInfo,true);
        $service = CustomerService::findOne(['yx_service_id'=>$rejectInfo['applyId']]);
        $service->yanxuan_status = 5;
        $service->zhongjing_status = 2;
        $time = time();
        $service->update_time = date('Y-m-d H:i:s',$time);
        $result1 = $service->save();
        $serviceLog = new ServiceLog();
        $serviceLog->service_id = $service->service_id;
        $serviceLog->log_time = date('Y-m-d',$time);
        $serviceLog->log_content = "客服审核不通过";
        $serviceLog->reason = $rejectInfo['rejectReason'];
        $result2 = $serviceLog->save();

        if($result1 && $result2){
            $transaction->commit();
        }else{
            $transaction->rollBack();
        }
    }

    public function cancelReturns($user_id,$service_no){
        $db=\Yii::$app->db;
        $transaction = $db->beginTransaction();
        $service = CustomerService::findOne(['service_no'=>$service_no,'user_id'=>$user_id]);
        $service->yanxuan_status = 6;
        $service->zhongjing_status = 1;
        $time = time();
        $service->update_time = date('Y-m-d H:i:s',$time);
        $result1 = $service->save();
        $serviceLog = new ServiceLog();
        $serviceLog->service_id = $service->service_id;
        $serviceLog->log_time = date('Y-m-d',$time);
        $serviceLog->log_content = "用户已取消申请";
        $result2 = $serviceLog->save();

        $package = Package::findOne($service->package_id);
        $package->package_status = 6;
        $result3 = $package->save();
        if($result1 && $result2 && $result3){
            $transaction->commit();
            $httpCurl = new HttpCurl();
            $httpCurl->rollpost("yanxuan.order.refund.cancel",['applyId'=>$service->yx_service_id]);
        }else{
            $transaction->rollBack();
        }
    }

    public function serviceExpress($user_id,$service_no,$express_company,$express_no){
        $db=\Yii::$app->db;
        $transaction = $db->beginTransaction();
        $service = CustomerService::findOne(['service_no'=>$service_no,'user_id'=>$user_id]);
        $service->yanxuan_status = 3;
        $service->zhongjing_status = 3;
        $service->return_express_company = $express_company;
        $service->return_express_no = $express_no;
        $time = time();
        $service->update_time = date('Y-m-d H:i:s',$time);
        $result1 = $service->save();
        $serviceLog = new ServiceLog();
        $serviceLog->service_id = $service->service_id;
        $serviceLog->log_time = date('Y-m-d',$time);
        $serviceLog->log_content = "用户已寄送商品，等待商家收货";
        $result2 = $serviceLog->save();
        if($result1 && $result2){
            $transaction->commit();
            $expressInfo[] = ['trackingCompany'=>$express_company,'trackingNum'=>$express_no];
            $httpCurl = new HttpCurl();
            $httpCurl->rollpost("yanxuan.order.refund.offer.express",['applyId'=>$service->yx_service_id,'expressInfo'=>json_encode($expressInfo)]);
        }else{
            $transaction->rollBack();
        }
    }

    public function expressConfirm($expressConfirm){
        $db=\Yii::$app->db;
        $transaction = $db->beginTransaction();
        $expressConfirm = json_decode($expressConfirm,true);
        $service = CustomerService::findOne(['yx_service_id'=>$expressConfirm['applyId']]);
        $service->yanxuan_status = 9;
        $service->zhongjing_status = 4;
        $time = time();
        $service->update_time = date('Y-m-d H:i:s',$time);
        $result1 = $service->save();
        $serviceLog = new ServiceLog();
        $serviceLog->service_id = $service->service_id;
        $serviceLog->log_time = date('Y-m-d',$time);
        $serviceLog->log_content = "商家已确认收货";
        $result2 = $serviceLog->save();
        if($result1 && $result2){
            $transaction->commit();
        }else{
            $transaction->rollBack();
        }
    }

    public function refundResult($refundResult){
        $db=\Yii::$app->db;
        $transaction = $db->beginTransaction();
        $refundResult = json_decode($refundResult,true);
        $service = CustomerService::findOne(['yx_service_id'=>$refundResult['applyId']]);
        $service->yanxuan_status = 4;
        $service->zhongjing_status = 5;
        $time = time();
        $service->update_time = date('Y-m-d H:i:s',$time);
        $result1 = $service->save();
        $serviceLog = new ServiceLog();
        $serviceLog->service_id = $service->service_id;
        $serviceLog->log_time = date('Y-m-d',$time);
        $serviceLog->log_content = "已退款成功";
        $result2 = $serviceLog->save();

        $package = Package::findOne($service->package_id);
        $package->package_status = 7;
        $result3 = $package->save();
        if($result1 && $result2 && $result3){
            $transaction->commit();
        }else{
            $transaction->rollBack();
        }
    }

    public function systemCancel($systemCancel){
        $db=\Yii::$app->db;
        $transaction = $db->beginTransaction();
        $systemCancel = json_decode($systemCancel,true);
        $service = CustomerService::findOne(['yx_service_id'=>$systemCancel['applyId']]);
        $service->yanxuan_status = 6;
        $service->zhongjing_status = 2;
        $time = time();
        $service->update_time = date('Y-m-d H:i:s',$time);
        $result1 = $service->save();
        $serviceLog = new ServiceLog();
        $serviceLog->service_id = $service->service_id;
        $serviceLog->log_time = date('Y-m-d',$time);
        $serviceLog->log_content = $systemCancel['errorMsg'];
        $result2 = $serviceLog->save();
        if($result1 && $result2){
            $transaction->commit();
        }else{
            $transaction->rollBack();
        }
    }

    public function exceptional($exceptionInfo){
        $db=\Yii::$app->db;
        $transaction = $db->beginTransaction();
        $exceptionInfo = json_decode($exceptionInfo,true);
        $order = Order::findOne(['order_no'=>$exceptionInfo['orderId']]);
        $time = date('Y-m-d H:i:s');
        $order->update_time = $time;
        $order->order_status = 2;
        $order->reject_reason = $exceptionInfo['reason'];
        $result2 = true;
        $packages = Package::findAll(['order_id'=>$order->order_id]);
        foreach($packages AS $key=>$value){
            $value->package_status = 3;
            $value->update_time = $time;
            $result2 &= $value->save();
        }
        $result1 = $order->save();
        if($result1 && $result2){
            $transaction->commit();
        }else{
            $transaction->rollBack();
        }
        file_put_contents(date("Ymd")."_exceptional.txt", json_encode($exceptionInfo)." 日期：".date("Y-m-d H:i:s",time()).PHP_EOL,FILE_APPEND);
    }

    public function serviceList($user_id){
        return CustomerService::find()
            ->select('service_no,yanxuan_status,sku_id,sku_pic,goods_name,sku_spec,sku_price,sku_num as num')
            ->where(['user_id'=>$user_id])
            ->orderBy('service_id desc')->asArray()->all();
    }

    public function serviceDetail($user_id,$service_no){
        $cs = CustomerService::find()
            ->select('service_id,service_no,service_time,order_no,yanxuan_status,reason_type,reason_detail,service_amount as return_money,customer_name,customer_phone')
            ->from('{{%customer_service}} cs')
            ->leftJoin('{{%order}} o', 'o.order_id=cs.order_id')
            ->where(['cs.user_id'=>$user_id,'service_no'=>$service_no])
            ->orderBy('service_id')->asArray()->one();
        $serviceLog = ServiceLog::find()->where(['service_id'=>$cs['service_id']])->asArray()->all();
        $serviceLogF = [];
        foreach ($serviceLog AS $key=>$value){
            if($value['reason']){
                $cs['reason'] = $value['reason'];
            }
            if($value['reciver']){
                $cs['reciver'] = $value['reciver'];
            }
            if($value['mobile']){
                $cs['mobile'] = $value['mobile'];
            }
            if($value['address']){
                $cs['address'] = $value['address'];
            }
            $serviceLogF[] = $value['log_time'] . " " . $value['log_content'];
        }
        $cs['content'] = $serviceLogF;
        if($cs['yanxuan_status'] == 1){
            $cs['service_status'] = 0;
        }elseif($cs['yanxuan_status']==2){
            $cs['service_status'] = 1;
        }elseif($cs['yanxuan_status']==3){
            $cs['service_status'] = 2;
        }elseif($cs['yanxuan_status']==9){
            $cs['service_status'] = 3;
        }elseif($cs['yanxuan_status']==4){
            $cs['service_status'] = 4;
        }elseif($cs['yanxuan_status']==5){
            $cs['service_status'] = 5;
        }elseif($cs['yanxuan_status']==6){
            $cs['service_status'] = 6;
        }
        return $cs;
    }

}
